<?php

namespace App\Miya\Models;

use App\Miya\Tools\TagTool;
use Illuminate\Database\Eloquent\Model;

class ModuleType extends Model
{
    protected $guarded = [];
    protected $casts = [
        'values' => 'json',
    ];

    public function getValuesAttribute($value)
    {
        return json_decode($value, true) ?: [];
    }

    public function setValuesAttribute($value)
    {
        $model = $this;
        $value = array_map(function ($value) use ($model) {
            if (empty($value['hash'])) {
                $str = $model->name . $value['value'];
                $value['hash'] = TagTool::makeTag($str, true);
            }
            return $value;
        }, $value);
        $this->attributes['values'] = json_encode(array_values($value));
    }

    public function module()
    {
        return $this->belongsTo(Module::class);
    }

    public function getValueListAttribute()
    {
        $data = [];
        array_map(function ($value) use (&$data) {
            $data[$value['hash']] = $value['value'];
        }, $this->values);

        return $data;
    }
}
